#include "stdafx.h"
#include "MainDlg.h"
#include "Settings.h"

HRESULT CMainDlg::initialize( IVdsService *pService )
{
	HRESULT hr = vdsList( pService, m_drives );
	CHECK0( hr );

	if( !m_info.SetCount( m_drives.GetCount() ) )
		return E_OUTOFMEMORY;

	for( size_t i = 0; i < m_drives.GetCount(); i++ )
	{
		hr = vdsDiskInfo( m_drives[ i ], m_info.GetData() + i );
		CHECK0( hr );
	}

	m_selectedIndex = -1;
	CString active;
	hr = settingRead( active );
	if( FAILED( hr ) )
		return S_FALSE;

	for( size_t i = 0; i < m_drives.GetCount(); i++ )
	{
		if( m_info[ i ].displayName != active )
			continue;
		m_selectedIndex = (int)i;
		break;
	}

	return S_OK;
}

LRESULT CMainDlg::onInitDialog( UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled )
{
	m_list.Attach( GetDlgItem( IDC_DRIVES ) );
	m_cb.Attach( GetDlgItem( IDC_ACTIVE ) );

	// Add columns
	m_list.AddColumn( L"Name", 0 );
	m_list.AddColumn( L"Size", 1 );
	m_list.AddColumn( L"Type", 2 );
	m_list.AddColumn( L"Status", 3 );

	// Add rows
	for( size_t i = 0; i < m_info.GetCount(); i++ )
	{
		// To the list
		const sDiskInfo& ds = m_info[ i ];
		m_list.AddItem( 0, 0, ds.displayName );
		m_list.AddItem( 0, 1, ds.getSizeString() );
		m_list.AddItem( 0, 2, ds.getTypeString() );
		m_list.AddItem( 0, 3, ds.getStateString() );

		// To the combobox
		m_cb.AddString( ds.displayName );
	}

	// Resize columns
	m_list.SetColumnWidth( 0, LVSCW_AUTOSIZE );
	m_list.SetColumnWidth( 1, LVSCW_AUTOSIZE );
	m_list.SetColumnWidth( 2, LVSCW_AUTOSIZE );
	m_list.SetColumnWidth( 3, LVSCW_AUTOSIZE );

	if( m_selectedIndex >= 0 )
		m_cb.SetCurSel( m_selectedIndex );

	return 0;
}

LRESULT CMainDlg::actOK( WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled )
{
	const int sel = m_cb.GetCurSel();
	if( sel < 0 )
	{
		MessageBox( L"Please select the disk for double click action" );
		return 0;
	}

	const CString active = m_info[ sel ].displayName;
	HRESULT hr = settingWrite( active );
	if( FAILED( hr ) )
	{
		MessageBox( L"Unable to save the settings.\n" + ErrorMessageW( hr ) );
		return 0;
	}

	EndDialog( IDOK );
	return 0;
}